import { useEffect, useState, useRef } from 'react';
import { Select, Input, Button } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';

import { SEARCH_TYPES } from '@/config';
import { SEARCH } from '@/config/url';

import styles from './index.module.scss';

export default props => {
  const initState = () => ({
    curType: SEARCH_TYPES[0].value,
    searchKey: 0,
  });
  const [state, setState] = useState(initState);
  const navigate = useNavigate();
  const searchRef = useRef(null);

  // 开始搜索
  const beginSearch = q => {
    const usp = new URLSearchParams();
    usp.set('type', state.curType);
    usp.set('q', q || '');

    // 跳转到搜索页面
    navigate(`${SEARCH}?${usp.toString()}`);

    // 非受控方式：通过更换 key 强制重新挂载以清空显示内容
    searchRef.current?.input?.blur?.();
    setState(o => ({ ...o, searchKey: o.searchKey + 1 }));
  };
  // 开始搜索
  const handleClickSearch = () => {
    const word = (searchRef.current?.input?.value || '').trim();
    beginSearch(word)
  };
  
  useEffect(() => {}, []);

  return (
    <div className={styles['container']}>
      <div className={styles['input-container']}>
        <Select
          className={styles['select']}
          value={state.curType}
          onChange={val => setState(o => ({...o, curType: val}))}
          options={SEARCH_TYPES}
          variant="borderless"
        />
        <Input.Search
            key={state.searchKey}
            ref={searchRef}
            onSearch={beginSearch}
            style={{width: '100%'}}
            placeholder='输入关键词搜索'
        />
        <Button onClick={handleClickSearch} className={styles['search-btn']} shape="circle" type="text" icon={<SearchOutlined/>}></Button>
      </div>
    </div>
  )
}
